﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using Newtonsoft.Json;
using EyFramework.Common.Utils;
using EyFramework.AutoCode.Entity;

namespace EyFramework.AutoCode
{
    public class PublicGlobal
    {
        public static readonly string dbSettingFile = DirectoryUtil.GetCurrentDirectory() + "\\AutoCode.json";

        public static DbConfigure DataBases = null;

        /// <summary>
        /// 将XML文件转成DataSet
        /// </summary>
        /// <returns></returns>
        public static DbConfigure GetDbConfigure()
        {
            DbConfigure configure = null;
            if (File.Exists(dbSettingFile))
            {
                //读取插件文件
                using (StreamReader sr = new StreamReader(dbSettingFile))
                {
                    try
                    {
                        JsonSerializer serializer = new JsonSerializer();
                        //构建Json.net的读取流  
                        JsonReader reader = new JsonTextReader(sr);
                        //对读取出的Json.net的reader流进行反序列化，并装载到模型中  
                        configure = serializer.Deserialize<DbConfigure>(reader);
                        reader.Close();
                        sr.Close();
                        if (configure.OracleDbs == null)
                        {
                            configure.OracleDbs = new List<OracleDb>();
                        }
                        if (configure.SqlserverDbs==null)
                        {
                            configure.SqlserverDbs = new List<SqlserverDb>();
                        }
                    }
                    catch (Exception ex)
                    {
                        throw new Exception(string.Format("解析{0}文件失败,{1}", dbSettingFile, ex.ToString()), ex);
                    }
                }
            }
            else
            {
                configure = new DbConfigure();
                configure.OracleDbs = new System.Collections.Generic.List<OracleDb>();
                configure.SqlserverDbs = new List<SqlserverDb>();
            }
            return configure;
        }
    }
}
